<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page 
	import="java.security.*"
	import="java.io.*"
	import="java.net.*"
	import="java.util.*"%>
<%
	//APP 정보
	final String APP_ID = "339258482837278";
	final String APP_SECRET = "d9d2ae415ae8a473823701f6655b6c53";
	final String REDIRECT_URI = URLEncoder.encode(String.valueOf(request.getRequestURL()), "UTF-8");
	final String PERMISSION_NAMES = "manage_pages,publish_stream,user_groups";
	
	String code = request.getParameter("code");
	
	//=====================================================
	// 토큰 요청
	//=====================================================
	if( code == null || code.equals("") ) {
		
		String key = this.getClass().getCanonicalName();
		String ukey = getUserKey(key);
		session.setAttribute("state", ukey);		//CSRF protection
		
		String redirectUrl = "https://www.facebook.com/dialog/oauth?"
			   + "client_id=" + APP_ID
			   + "&redirect_uri=" + REDIRECT_URI
			   + "&scope=" + PERMISSION_NAMES
			   + "&state=" + ukey;
		
		response.sendRedirect(redirectUrl);
		
		return;
	} 
	//=====================================================
	
	
	//=====================================================
	// 액세스 토큰 요청
	//=====================================================
	String state = request.getParameter("state");
	if( state.equals(String.valueOf(session.getAttribute("state"))) ) {
		
		//액세스 토큰을 가져온다.
		//액세스 토큰을 새로 생성한다.
		String tokenUrl = "https://graph.facebook.com/oauth/access_token?"
		       + "client_id=" + APP_ID 
		       + "&redirect_uri=" + REDIRECT_URI
		       + "&client_secret=" + APP_SECRET 
		       + "&code=" + code;
		
		int resultCode;
		
		HttpURLConnection conn = null;
		InputStream is = null;
		BufferedReader br = null;
		
		StringBuffer responseXml = new StringBuffer();
		try {
			URL url = new URL(tokenUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setConnectTimeout(2000);
			conn.setReadTimeout(12000);
			conn.setInstanceFollowRedirects(false);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlendcoded");
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.connect();
	
			try {
				is = conn.getInputStream();
				resultCode = conn.getResponseCode();
			} catch (Exception e) {
				is = conn.getErrorStream();
				resultCode = conn.getResponseCode();
			}
	
			br = new BufferedReader(new InputStreamReader(is));
			String line;
			while ((line = br.readLine()) != null) {
				responseXml.append(line);
			}
			is.close();
			
			String json = responseXml.toString();
			
			String[] arr = json.split("&");
			for (int i = 0; i < arr.length; i++) {
				String[] temp = arr[i].split("=");
				if (temp[0].equals("access_token")) {
					String accessToken = temp[1];
					
					//세션에 저장
//					System.out.print("access_token: " + accessToken);
					session.setAttribute("access_token", accessToken);
					application.setAttribute("access_token", accessToken);
					
				}
				if (temp[0].equals("expires")) {
					String expires = temp[1];
					
					//세션에 저장
					//System.out.print("expires: " + expires);
					session.setAttribute("access_expires", expires);
				}
			}
			
			response.sendRedirect("server.jsp");
			
		} catch (MalformedURLException me) {
			me.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			if(br!=null) try { br.close(); }catch(Exception e) { }
			if(is!=null) try { is.close(); }catch(Exception e) { }
			if(conn!=null) try { conn.disconnect(); }catch(Exception e) { }
		}
		
		/* markan.ServerLiveCheck serverLiveCheck = new markan.ServerLiveCheck();
		if(serverLiveCheck.checkServer()==200) {
			out.println("서버 살아있음.");
		} else {
			out.println("삼가 서버의 명복을 빕니다.");
		} */
			
		markan.PostSubmit postSubmit = new markan.PostSubmit();
		postSubmit.send("https://graph.facebook.com/186577728129797/feed?access_token=" + session.getAttribute("access_token"), "테스트!!");
		
	} else {
		//throw new Exception("The state does not match. You may be a victim of CSRF.");
		response.sendRedirect("/index.jsp");
	}
	//=====================================================
%>


<%!
//=====================================================
// 메소드 영역
//=====================================================
	
/**
 * md5 로 암호화
 * @param str
 * @return
 */
public String getMD5(String nonce) {
	StringBuffer sb = new StringBuffer();
	try {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update(nonce.getBytes());
		byte[] buf = md5.digest();
		
		for (int i = 0, len = buf.length; i < len; i++) {
			sb.append(String.format("%02X", 0xFF & buf[i]));
		}
		
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
	
	return sb.toString();
}

/**
 * 유니크한 UserKey 를 생성한다.
 * @param key
 * @return
 */
public String getUserKey(String key) {
	
	long timestamp = new Date().getTime();
	String ukey = getMD5(String.valueOf(timestamp) + key);

	return ukey;
}
%>